package ui;

import entity.MainJFrame;
import entity.User;
import util.JsonRW;
import util.FileDeal;
import util.GUIUtil;
import util.UserManager;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.Ellipse2D;
import java.io.File;

/**
 * 按下Tab键切换焦点
 */
public class LoginGUI extends MainJFrame {
    private JTextField usernameTextField;
    private JPasswordField passwordTextField;

    private User lastLoginUser;

    // 颜色定义
    private final Color PRIMARY_COLOR = new Color(66, 133, 244);
    private final Color SECONDARY_COLOR = new Color(234, 67, 53);
    private final Color BG_COLOR = new Color(245, 245, 245);
    private final Color TEXT_COLOR = new Color(66, 66, 66);
    private final Color FIELD_BG = new Color(255, 255, 255);
    private final Color FIELD_BORDER = new Color(218, 220, 224);

    public void setTextContent(String username, String password) {
        usernameTextField.setText(username);
        passwordTextField.setText(password);
    }

    public LoginGUI() {
        super();

        initTextField();

        String lastUserStr = (String) JsonRW.get(JsonRW.historyFile, "lastLoginUsername");
        if (lastUserStr != null && !lastUserStr.isEmpty()) {
            UserManager.loadUserFromFile();
            lastLoginUser = UserManager.getUser(lastUserStr);
            if (lastLoginUser != null) {
                usernameTextField.setText(lastLoginUser.getUsername());
            }
        }
        initComponents();

        enableInputMethods(false);
        setSize(450, 450);
        setLocationRelativeTo(null);
        setVisible(true);

        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                if (keyCode == KeyEvent.VK_ENTER) {
                    loginVerify();
                }
            }
        });
    }

    private void initTextField() {
        this.usernameTextField = GUIUtil.createStyledTextField(20, FIELD_BORDER, FIELD_BG);
        this.passwordTextField = GUIUtil.createStyledPasswordField(20, FIELD_BORDER, FIELD_BG);


        passwordTextField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    loginVerify();
                }
            }
        });
    }

    @Override
    public void updateMenuBar() {
        JMenu functionMenu = getFunctionMenu();
        functionMenu.add(new JMenuItem("注销账号"));
        functionMenu.add(new JMenuItem("退出登录"));
        functionMenu.add(new JSeparator());
    }

    @Override
    public void initComponents() {
        getContentPane().setBackground(BG_COLOR);
        setLayout(new BorderLayout(0, 10));
        ((JComponent) getContentPane()).setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        setTop();
        setTextFields();
        setButtons();
    }

    @SuppressWarnings("all")
    private void setTextFields() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(BG_COLOR);

        // 显示上次登录账号的头像
        if (lastLoginUser != null) {

            // 创建头像面板
            JPanel avatarPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
            avatarPanel.setBackground(BG_COLOR);

            // 尝试加载头像
            ImageIcon avatarIcon = loadUserAvatar(lastLoginUser.getUsername());

            // 绘制圆形裁剪的图像
            // 如果没有头像，绘制默认的用户图标
            // 绘制边框
            JLabel avatarLabel = getAvatarLabel(avatarIcon);

            avatarPanel.add(avatarLabel);
            avatarPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 20, 0));

            panel.add(avatarPanel, BorderLayout.NORTH);
        } else {
            // 如果没有上次登录用户，显示欢迎图标
            JPanel welcomePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
            welcomePanel.setBackground(BG_COLOR);

            JLabel welcomeIcon = getWelcomeIcon();
            welcomePanel.add(welcomeIcon);
            welcomePanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 20, 0));
            panel.add(welcomePanel, BorderLayout.NORTH);
        }

        // 创建文本字段面板
        JPanel textFieldPanel = new JPanel();
        textFieldPanel.setBackground(BG_COLOR);
        textFieldPanel.setLayout(new GridBagLayout());
        textFieldPanel.setBorder(BorderFactory.createEmptyBorder(10, 30, 10, 30));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(10, 5, 10, 5);
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0.3;

        // 用户名标签和输入框
        textFieldPanel.add(createFieldLabel("用户名:"), gbc);
        gbc.gridx = 1;
        gbc.weightx = 0.7;
        gbc.gridwidth = 2;
        textFieldPanel.add(usernameTextField, gbc);

        // 密码标签和输入框
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0.3;
        gbc.gridwidth = 1;
        textFieldPanel.add(createFieldLabel("密码:"), gbc);
        gbc.gridx = 1;
        gbc.weightx = 0.7;
        gbc.gridwidth = 2;
        textFieldPanel.add(passwordTextField, gbc);

        panel.add(textFieldPanel, BorderLayout.CENTER);
        add(panel, BorderLayout.CENTER);
    }

    private JLabel getWelcomeIcon() {
        JLabel welcomeIcon = new JLabel() {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                int diameter = 80;
                g2.setColor(PRIMARY_COLOR);
                g2.fillOval(0, 0, diameter, diameter);

                g2.setColor(Color.WHITE);
                g2.setFont(new Font("微软雅黑", Font.BOLD, 30));
                g2.drawString("👋", 20, 50);
            }
        };

        welcomeIcon.setPreferredSize(new Dimension(80, 80));
        return welcomeIcon;
    }

    private JLabel getAvatarLabel(ImageIcon avatarIcon) {
        JLabel avatarLabel = new JLabel() {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                int diameter = Math.min(getWidth(), getHeight());

                if (avatarIcon != null) {
                    // 绘制圆形裁剪的图像
                    Shape circle = new Ellipse2D.Float(0, 0, diameter, diameter);
                    g2.setClip(circle);
                    g2.drawImage(avatarIcon.getImage(), 0, 0, diameter, diameter, null);
                    g2.setClip(null);
                } else {
                    // 如果没有头像，绘制默认的用户图标
                    g2.setColor(PRIMARY_COLOR);
                    g2.fillOval(0, 0, diameter, diameter);

                    g2.setColor(Color.WHITE);
                    g2.setFont(new Font("微软雅黑", Font.BOLD, diameter / 2));
                    FontMetrics fm = g2.getFontMetrics();
                    String initial = lastLoginUser.getUsername().substring(0, 1).toUpperCase();
                    int x = (diameter - fm.stringWidth(initial)) / 2;
                    int y = (diameter - fm.getHeight()) / 2 + fm.getAscent();
                    g2.drawString(initial, x, y);
                }

                // 绘制边框
                g2.setColor(FIELD_BORDER);
                g2.setStroke(new BasicStroke(2));
                g2.drawOval(0, 0, diameter, diameter);
            }
        };

        avatarLabel.setPreferredSize(new Dimension(100, 100));
        avatarLabel.setToolTipText("上次登录用户: " + lastLoginUser.getUsername());
        return avatarLabel;
    }

    /**
     * 加载用户头像
     */
    private ImageIcon loadUserAvatar(String username) {
        try {
            String avatarPath = JsonRW.getStr(JsonRW.configFile, "userDataDir") + "/" + username + "/avatar/0.png";
            File avatarFile = new File(avatarPath);

            if (avatarFile.exists()) {
                ImageIcon originalIcon = new ImageIcon(avatarPath);
                Image scaledImage = originalIcon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH);
                return new ImageIcon(scaledImage);
            }

            // 尝试加载默认头像
            String defaultAvatarPath = JsonRW.getStr(JsonRW.configFile, "defaultAvatar");
            if (!defaultAvatarPath.isEmpty()) {
                File defaultAvatarFile = new File(defaultAvatarPath);
                if (defaultAvatarFile.exists()) {
                    ImageIcon originalIcon = new ImageIcon(defaultAvatarPath);
                    Image scaledImage = originalIcon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH);
                    return new ImageIcon(scaledImage);
                }
            }
        } catch (Exception e) {
            System.err.println("加载头像失败: " + e.getMessage());
        }

        return null;
    }

    private void setTop() {
        JPanel panel = new JPanel();
        panel.setBackground(BG_COLOR);
        JLabel label = GUIUtil.createStyledLabel("拼图游戏 - 登录", 24, PRIMARY_COLOR);
        label.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
        panel.add(label);
        add(panel, BorderLayout.NORTH);
    }

    private void setButtons() {
        JPanel panel = new JPanel();
        panel.setBackground(BG_COLOR);
        panel.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 10));

        JButton registerButton = GUIUtil.createStyledButton("注册账号", SECONDARY_COLOR, 120, 40);
        registerButton.addActionListener(_ -> {
            String usernameTextFieldText = usernameTextField.getText();
            RegisterGUI registerGUI = new RegisterGUI();
            if (!UserManager.userExists(usernameTextFieldText)) {
                registerGUI.setTextField(usernameTextFieldText, "", "", "");
            }
            dispose();
        });

        // 组件
        JButton loginButton = GUIUtil.createStyledButton("登录", PRIMARY_COLOR, 120, 40);
        loginButton.addActionListener(_ -> loginVerify());

        panel.add(registerButton);
        panel.add(loginButton);

        add(panel, BorderLayout.SOUTH);
    }

    private void loginVerify() {
        String username = usernameTextField.getText().toLowerCase();
        String password = new String(passwordTextField.getPassword());
        UserManager.loadUserFromFile();
        if (UserManager.userExists(username)) {
            User user = UserManager.getUser(username);
            if (user == null) {
                showErrorDialog("该用户不存在，请前往注册！");
                return;
            }
            if (user.getPassword().equals(password)) {
                UserManager.setOnlineUser(user);
                JsonRW.saveLastUser(username);

                // 清空上次运行目录
                FileDeal.deleteDirectory(new File(JsonRW.getStr(JsonRW.configFile, "runPath")));
                new GameGUI();
                dispose();
            } else {
                showErrorDialog("用户名或密码错误！");
            }
        } else {
            showErrorDialog("该用户不存在，请前往注册！");
        }
    }

    // 辅助方法：创建字段标签
    private JLabel createFieldLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        label.setForeground(TEXT_COLOR);
        return label;
    }

    // 辅助方法：创建样式化文本框



    // 辅助方法：显示错误对话框
    private void showErrorDialog(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }
}